//
//  ICSendMessageHelper.m
//  ICome
//
//  Created by zhangrongwu on 16/10/19.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICSendMessageHelper.h"
#import "ICChatSocketManager.h"

@implementation ICSendMessageHelper
// chat中 发送消息
+(void)sendMessageWithObject:(NSDictionary *)param
                  identifier:(NSString *)identifier
                     Success:(SendSuccessCompletionHandle)success
                     Failure:(SocketFailureCompletionHandle)failure {
    [[ICChatSocketManager sharedInstance] sendMessageWithParam:param identifier:identifier Success:^(id object, id other) {
        success(object, other);
        [ICSendMessageHelper updateMessageStatus:YES object:object other:other];
    } Failure:^(NSError *error, id other) {
        failure(error, other);
        [ICSendMessageHelper updateMessageStatus:NO object:nil other:other];
    }];
}

+ (void)updateMessageStatus:(BOOL)success object:(id)object other:(id)other {
    NSString *identify = other[@"identify"];
    ICMessage *message = [[ICMessage alloc] init];
    // 消息发送成功失败不同处理
    if (success) {
        message.deliveryState = ICMessageDeliveryState_Delivered;
        message.messageId = [object objectForKey:@"id"];
        message.to = [object objectForKey:@"gId"];
        message.date = [[object objectForKey:@"st"] integerValue];// 服务器时间
    } else {
        message.deliveryState = ICMessageDeliveryState_Failure;
        message.messageId = identify;
        message.date = [ICMessageHelper currentMessageTime];// 本地时间
    }
    [ICMessageDatabase updateMessage:message identifier:identify];
    // 发送成功后刷新数据 -- 针对发送界面被delloc 后重新进入聊天界面的操作
    NSDictionary *info = @{@"identify":identify,
                           @"deliveryState":@(message.deliveryState)};
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationUpdateMessageStateRefresh object:info];
}


@end
